﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Routine.API.Models;
using Routine.API.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Routine.API.Controllers
{
    [Route("api/companies/{companyId}/employees")]
    public class EmployeesController : ControllerBase
    {
        private readonly IMapper mapper;
        private readonly ICompanyRepository companyRepository;

        public EmployeesController(IMapper mapper, ICompanyRepository companyRepository)
        {
            this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            this.companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<EmployeeDto>>> GetEmployeesForCompany(Guid companyId,
            [FromQuery]string genderDisplay, string q)
        {
            if (!await companyRepository.CompanyExistsAsync(companyId))
                return NotFound();

            var employees = await companyRepository.GetEmployeesAsync(companyId, genderDisplay, q);
            if (!employees.Any())
            {
                return NotFound();
            }

            return Ok(mapper.Map<IEnumerable<EmployeeDto>>(employees));
        }

        [HttpGet("{employeeId}")]
        public async Task<ActionResult<EmployeeDto>> GetEmployeeForCompany(Guid companyId, Guid employeeId)
        {
            if (!await companyRepository.CompanyExistsAsync(companyId))
                return NotFound();

            var employee = await companyRepository.GetEmployeeAsync(companyId, employeeId);
            if (employee != null)
                return Ok(mapper.Map<EmployeeDto>(employee));
            return NotFound();
        }
    }
}
